package org.example.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.Jwt;
import org.example.utils.Result;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/api/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        // 获取请求的url
        String url = req.getRequestURL().toString();
        // 判断url是否包含login或register，如果包含则放行
        if (url.contains("login") || url.contains("register")) {
//            log.info("登录或者注册，放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 获取请求头中的令牌jwt
        String token = req.getHeader("Authorization");
        // 判断令牌是否存在，如果不存在，返回错误结果未登录
        if (!StringUtils.hasLength(token)) {
//            log.info("请求头token为空，用户未登录");
            resp.setStatus(401);
            return;
        }
        // 校验jwt是否生效
        try {
            Jwt.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
//            log.info("解析token失败");
            resp.setStatus(401);
            return;
        }
        // 放行
//        log.info("jwt令牌合法，放行");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
